import sys
sys.path.append('../../')
import redis
from Utility.UpdateBasicData import *
import os
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
os.environ['NUMEXPR_MAX_THREADS'] = '16'
import numpy as np
def saveDataToRedis(data,redis_key):
    redis_client = redis.StrictRedis(host='127.0.0.1')
    modifiedData = data.to_msgpack()
    redis_client.set(redis_key, modifiedData)
    pass
def getDataFromRedis(redis_key):
    redis_client = redis.StrictRedis(host='127.0.0.1')
    data=redis_client.get(redis_key)
    if data!=None:
        data=pd.read_msgpack(data)
    else:
        data=pd.DataFrame()
    return data

#获取股票列表，主要为中证800+额外持仓的股票
filename=os.path.join(LocalFileAddress,'312_20200224.h5')
with pd.HDFStore(filename,'r',complib='blosc:zstd',append=False,complevel=9) as store:
    myStocks=store['data']

select=['002456.SZ',
'601066.SH',
'000001.SZ',
'000063.SZ',
'000100.SZ',
'000333.SZ',
'000625.SZ',
'000651.SZ',
'002027.SZ',
'002074.SZ',
'002299.SZ',
'002384.SZ',
'002415.SZ',
'002508.SZ',
'002555.SZ',
'002563.SZ',
'300059.SZ',
'300558.SZ',
'600030.SH',
'600036.SH',
'600068.SH',
'600201.SH',
'600340.SH',
'600547.SH',
'600612.SH',
'600690.SH',
'600741.SH',
'600809.SH',
'600837.SH',
'600887.SH',
'601021.SH',
'601318.SH',
'601688.SH',
'601838.SH',
'601888.SH',
'601933.SH',
'603833.SH',]

filename=os.path.join(LocalFileAddress,'312_20200224.h5')
with pd.HDFStore(filename,'r',complib='blosc:zstd',append=False,complevel=9) as store:
    myStocks=store['data']

myStocks=myStocks[myStocks['code'].isin(select)]
myStocks['marketValue']=myStocks['hold']*myStocks['price']
cash=myStocks['marketValue'].sum()

codes=list(myStocks['code'])
parameters={'targetType':'125mixed',
        'dataPath':r'C:/predictData/strategy20191228',
        'myStocks':myStocks,
        'h5':False,
        'redis':False,
        'influxdb':True,
        'totalCash':cash,
        'predictDatabase':'MaoTickPredict1m2m5m8003weeks',
        'transactionRatio':0.8,
        'maxExposureRatio':0.5,
        'maxVolumeEachTimeRatio':0.25,
        'parameter1':list(0.0001*np.arange(10,80,10)),
        'parameter2':list(0.01*np.arange(10,80,10))
        }


redis_key='312-20200309'
startDate=20190701
endDate=20200306

days=list(TradedayDataProcess.getTradedays(startDate, endDate))
raw=[]
for day in days:
    redis_key0=redis_key+'s'+str(day)+'-'+str(day)
    daily=getDataFromRedis(redis_key0)
    raw.append(daily)
    #print(f"{redis_key0} complete!")
print("complete!")

selectList=codes
#selectList=['601066.SH']

total=pd.concat(raw)
total=total[total['code'].isin(selectList)]
total['weight']=1
total=total[total['count']>0]
total['profit']=total['profit']-0.5*total['slip']
#total=total[total['code'].isin(select)]
#total=raw[10]
#total=total[(total['date']>='20190701') & (total['date']<='20190930')]
#total=total[total['code'].isin(choose)]
#total=total[(total['date']>='20180101') & (total['date']<='20190331')]
#total=total[(total['date']=='20200228')|(total['date']=='20200123')  ]


middledays='20200101'
before=total[total['date']<middledays]

totaldays=len(before['date'].unique())
dfall=[]
for code in codes:
    total0=before[before['code']==code]
    record=[]
    for p1 in parameters['parameter1']:
        for p2 in parameters['parameter2']:
            data0=total0[(total0['parameter1']==p1) & (total0['parameter2']==p2)]
            windays=data0[data0['yieldToAll']>0].shape[0]
            if (windays>0):
                winratio=windays/data0.shape[0]
                record.append({'code':code,'parameter1':p1,'parameter2':p2,'openDays':data0.shape[0],'winDays':windays,'totalyield':data0['yieldToAll'].sum(),'winRatio':winratio})
    df=pd.DataFrame(record)
    df=df.sort_values(by="totalyield" , ascending=False) 
    if (df.shape[0]>0):
        df=df[(df['totalyield']>0) & (df['winRatio']>0.5)].head(1)
        dfall.append(df)
dfall=pd.concat(dfall)
#print(dfall)

after=total[total['date']>=middledays]
totaldays=len(after['date'].unique())
record=[]
detail=[]
for code in codes:
    total0=after[after['code']==code]
    p=dfall[dfall['code']==code].head(1)
    if ((p.shape[0]>0) and (total0.shape[0]>0)):
        p1=p['parameter1'].iloc[0]
        p2=p['parameter2'].iloc[0]
        profitlast=p['totalyield'].iloc[0]
        data0=total0[(total0['parameter1']==p1) & (total0['parameter2']==p2)]
        totalyield=data0['yieldToAll'].sum()
        detail.apped(data0)
        record.append({'code':code,'parameter1':p1,'parameter2':p2,'totalyield':totalyield,'lastyield':profitlast})
df=pd.DataFrame(record)
df=df.sort_values(by="totalyield" , ascending=False) 
#print(df)
detail=pd.concat(detail)


